package com.oswift.cms.web.backstage;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CommonModelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.DownloadBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.service.IChannelService;
import com.oswift.cms.service.IDownloadService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class DownloadAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(DownloadAction.class);

    /**
     * DownloadServiceImpl注入对象
     */
    @Resource
    private IDownloadService downloadService;

    /**
     * ChannelServiceImpl注入对象
     */
    @Resource
    private IChannelService channelService;

    /**
     *
     * 加载下载新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddDownload", method = RequestMethod.GET)
    public ModelAndView loadAddDownload(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = downloadService.loadAddDownload(PageName.DOWNLOAD, companyId);
            mv.addObject(METHOD, METHOD_ADD);
        }
        catch (PlatException e)
        {
            log.error("The method of loadAddDownload is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadAddDownload is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 加载下载修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateDownload", method = RequestMethod.GET)
    public ModelAndView loadUpdateDownload(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = downloadService.loadUpdateDownload(PageName.DOWNLOAD,
                    companyId, Integer.valueOf(id));
            mv.addObject(METHOD, METHOD_UPDATE);
        }
        catch (PlatException e)
        {
            log.error("The method of loadUpdateDownload is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadUpdateDownload is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 添加下载信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addDownload", method = RequestMethod.POST)
    @ResponseBody
    public Object addDownload(HttpServletRequest request, DownloadBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(bean.getTitle())
                    || StringUtil.isEmpty(bean.getDownloadUrl())
                    || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            AdminBean adminBean = getAdmin(request);
            bean.setCompanyId(adminBean.getCompanyID());
            bean.setTableName(Field.TableName.DOWNLOAD);
            bean.setInputer(adminBean.getAdminName());
            if(StringUtil.isEmpty(bean.getDefaultPicUrl()))
            {
                bean.setDefaultPicUrl(null);
            }

            boolean isSuccess = downloadService.save(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.DOWNLOAD_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.DOWNLOAD_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.DOWNLOAD_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of addDownload is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of addDownload is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 添加下载信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updateDownload", method = RequestMethod.POST)
    @ResponseBody
    public Object updateDownload(DownloadBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (bean.getCommonModelId() <= 0)
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getTitle()) || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            boolean isSuccess = downloadService.update(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.DOWNLOAD_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.DOWNLOAD_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.DOWNLOAD_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of updateDownload is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of updateDownload is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 删除下载信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delDownload", method = RequestMethod.POST)
    @ResponseBody
    public Object delDownload(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }
            int delSuccessNum = 0;
            int delFailNum = 0;
            String[] array = id.split(Field.COMMA);
            for (String i : array)
            {
                boolean isSuccess = downloadService.delete(Integer.valueOf(i));
                if (isSuccess)
                {
                    delSuccessNum++;
                }
                else
                {
                    delFailNum++;
                }
            }
            if (delSuccessNum == array.length)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.DOWNLOAD_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.DOWNLOAD_DEL_FAIL);
                String mess = ResourceManager
                        .getValue(PageCode.DOWNLOAD_DEL_FAIL);
                messBean.setContent(StringUtil.replace(mess, String
                        .valueOf(delSuccessNum), String.valueOf(delFailNum)));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of delDownload is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of delDownload is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 获取公共内容信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getDownloadList", method = RequestMethod.GET)
    public ModelAndView getArticleList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String orderField = request.getParameter("orderField");
            String orderType = request.getParameter("orderType");
            String s_Status = request.getParameter("status");
            String s_ChannelId = request.getParameter("channelId");
            String searchType = request.getParameter("searchType");
            String keyword = request.getParameter("keyword");
            String s_PageNum = request.getParameter("pageNum");

            int status = Field.Status.ALL;
            if (!StringUtil.isEmpty(s_Status))
            {
                status = Integer.valueOf(s_Status);
            }
            int channelId = -1;
            if (!StringUtil.isEmpty(s_ChannelId))
            {
                channelId = Integer.valueOf(s_ChannelId);
            }
            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(s_PageNum))
            {
                pageNum = Integer.valueOf(s_PageNum);
            }

            // 权限判断
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            PageBean<CommonModelBean> bean = downloadService.getCommonModel(orderField,
                    orderType, status, channelId, searchType, keyword,
                    this.pageRecordNum, pageNum, Field.TableName.DOWNLOAD,
                    companyId);

            // 获取包含文章板块的栏目
            DictionaryBean dictionaryBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_DOWNLOAD_KEY);
            List<ChannelBean> channelList = channelService.getChannelList2(
                    companyId, dictionaryBean.getFieldValue());

            mv = new ModelAndView(PageName.DOWNLOADLIST);
            mv.addObject("pageBean", bean);
            mv.addObject("status", status);
            mv.addObject("channels", channelList);
            mv.addObject("orderType", orderField + "_" +orderType);
            mv.addObject("channelId", channelId);
        }
        catch (PlatException e)
        {
            log.error("Get DownloadList info is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            bean.setUrl("getDownloadList.html");
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 下载详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/downloadDetail", method = RequestMethod.GET)
    public ModelAndView downloadDetail(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }

            DownloadBean bean = downloadService.getOne(Integer.valueOf(id));
            mv = new ModelAndView(PageName.DOWNLOAD_DETAIL);
            mv.addObject("downloadBean", bean);
        }
        catch (PlatException e)
        {
            log.error("The method of downloadDetail is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of downloadDetail is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    public void setDownloadService(IDownloadService downloadService)
    {
        this.downloadService = downloadService;
    }

    public void setChannelService(IChannelService channelService)
    {
        this.channelService = channelService;
    }
}